const { app, BrowserWindow, Menu, screen, Tray } = require("electron");
const initModules = require("./modules");
const path = require("node:path");

let _screenWidth, _screenHeight;

//是否是测试环境
const isDevelopment = !app.isPackaged;

//排除警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

//解决应用程序冲突
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
	app.quit();
}

//关闭自带菜单
Menu.setApplicationMenu(null);

//开启主窗口：按钮面板，贴边收起
function createMainWindow() {
	const window = new BrowserWindow({
		focusable: false,
		width: 66,
		height: 420,
		x: 0,
		y: (_screenHeight - 420) / 2,
		titleBarStyle: "hidden",
		resizable: false,
		movable: false,
		minimizable: false,
		maximizable: false,
		closable: false,
		alwaysOnTop: true,
		transparent: true,
		backgroundColor: "#00000000",
		webPreferences: {
			preload: path.join(__dirname, "preload.js"),
		},
	});
	if (isDevelopment) {
		window.loadURL("http://localhost:7758");
	} else {
		window.loadFile(path.join(__dirname, "platform/index.html"), {
			hash: "",
		});
	}

	//隐藏任务栏
	window.setSkipTaskbar(true);

	//设置置顶
	// window.setAlwaysOnTop(true, "normal");
	//是否打开调试工具
	// window.webContents.openDevTools()
}

//程序环境准备好时触发
app.whenReady().then(() => {
	//获取屏幕宽高
	_screenWidth = screen.getPrimaryDisplay().bounds.width;
	_screenHeight = screen.getPrimaryDisplay().bounds.height;
	createMainWindow();
	initModules();
	//程序被激活，如果目前没有窗口，则创建主窗口
	app.on("activate", function () {
		if (BrowserWindow.getAllWindows().length === 0) createMainWindow();
	});
	//创建托盘
	const tray = new Tray(path.join(__dirname, "assets/PlantB.ico"));
	const contextMenu = Menu.buildFromTemplate([
		{
			label: "退出应用",
			click: () => {
				app.exit();
			},
		},
	]);
	tray.setToolTip("PlantB");
	tray.setContextMenu(contextMenu);
});

app.on("ready", function () {});

//如果所有的窗口都关闭
app.on("window-all-closed", function () {
	if (process.platform !== "darwin") app.quit();
});

//设置程序ID
app.setAppUserModelId("PlanBPlus");

//如果是测试环境，开启热部署
if (isDevelopment) {
	try {
		require("electron-reloader")(module);
	} catch (err) {}
}
